package com.xrh.xdemo.service.utils;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xrh.core.utils.XAssert;
import com.xrh.xdemo.api.constants.LoginConstants;
import com.xrh.xdemo.api.dto.extend.SysUserDetailDTO;
import com.xrh.xdemo.service.service.SysUserService;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;

public class LoginUtils {

    //用户信息 , 存放在request中的key
    public final static String REQUEST_USER_KEY = "request_user_key";
    
    /**
     * @throws Exception
     * @function 获取用户信息
     * @author 肖荣辉
     * @date 2021年7月6日
     */
    public static SysUserDetailDTO getUserByRequest(HttpServletRequest request) {

        Object userObj = request.getAttribute(REQUEST_USER_KEY);
        
        if(userObj != null)
        	return (SysUserDetailDTO) userObj;

        String token = request.getHeader(LoginConstants.JWT_LOGIN_TOKEN_KEY);

        if (StrUtil.isBlank(token))
            return null;
        
        SysUserDetailDTO dto = parseByToken(token) ;

        request.setAttribute(REQUEST_USER_KEY, dto);
        
        return dto;
    }
    
    /**
	 * @function 从token中获取用户信息
	 * @param token
	 * @author 肖荣辉
	 * @date 2023年12月8日
	*/
    public static SysUserDetailDTO parseByToken(String token) {
    	
    	//解析token
		JWT jwt = JWTUtil.parseToken(token);
		
		//验证token是否合法有效
		if(!jwt.setKey(LoginConstants.JWT_LOGIN_USER_KEY.getBytes()).verify()){
	 		return null;
	 	}
		
		//验证token的有效期是否有效
		if(!jwt.validate(0)){
	 		return null;
	 	}
		
		//获取用户id
		Long userId = Convert.convert(Long.class, jwt.getPayload(LoginConstants.JWT_LOGIN_USER_ID_KEY));
		
		SysUserService sysUserService = SpringUtil.getBean(SysUserService.class);
		
		String loginInfo = sysUserService.getSysUserLoginInfo(userId);
		
		XAssert.isTrue(StrUtil.isNotBlank(loginInfo), "用户已被删除 , 无法获取登录信息");

		String unsecretLoginInfo = ZipUtil.unGzip(Base64.decode(loginInfo), "utf-8");
		
		return JSONUtil.toBean(unsecretLoginInfo, SysUserDetailDTO.class); 
    }
    
    /**
     * @function  获取用户登录信息
     * @author 肖荣辉
     * @date 2021年7月6日
     */
    public static SysUserDetailDTO getUser() {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attributes == null)
            return null;

        HttpServletRequest request = attributes.getRequest();

        return getUserByRequest(request);

    }
    
    
    
    /**
	 * @function 设置登录信息到request中
	 * @param user
	 * @author 肖荣辉
	 * @date 2024年1月5日
	*/
    public static void setLoginInfoToRequest(SysUserDetailDTO user) {
    	
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attributes == null)
            return;

        HttpServletRequest request = attributes.getRequest();
        
        request.setAttribute(REQUEST_USER_KEY, user);
    }
	
	
}
